package com.videomeetting.legend.videomeetting.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.graphics.drawable.ClipDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.videomeetting.legend.videomeetting.R;
import com.videomeetting.legend.videomeetting.activity.adapater.FileChooseAdapater;
import com.videomeetting.legend.videomeetting.activity.base.BaseApplication;
import com.videomeetting.legend.videomeetting.activity.bean.MessageEvent;
import com.videomeetting.legend.videomeetting.activity.bean.VideoBean;
import com.videomeetting.legend.videomeetting.activity.fragment.FileChooseFragment;
import com.videomeetting.legend.videomeetting.activity.service.HdmiSecService;
import com.videomeetting.legend.videomeetting.activity.utils.EthernetInfo;
import com.videomeetting.legend.videomeetting.activity.utils.MyUtils;
import com.videomeetting.legend.videomeetting.activity.view.MyDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.video.stream.Mmixer;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.ContentValues.TAG;

/**
 * Created by legend on 18-6-7.
 */

public class ControlActivity extends FragmentActivity implements View.OnClickListener {
    @BindView(R.id.activity_control_setting_btn)
    Button settingtn;
    @BindView(R.id.activity_controlsurface_one)
    SurfaceView surfaceViewOne;
    @BindView(R.id.activity_controlsurface_two)
    SurfaceView surfaceViewTwo;
    @BindView(R.id.activity_controlsurface_three)
    SurfaceView surfaceViewThree;
    @BindView(R.id.activity_controlsurface_four)
    SurfaceView surfaceViewFour;
    @BindView(R.id.activity_controlsurface_five)
    SurfaceView surfaceViewFive;
    @BindView(R.id.activity_control_right_surface_left)
    SurfaceView surfaceViewLeft;
    @BindView(R.id.activity_control_right_surface_right)
    SurfaceView surfaceViewRight;
    @BindView(R.id.activity_control_input_voice_img)
    ImageView inputVoiceImg;
    @BindView(R.id.activity_control_intput_voice_handle)
    SeekBar inputVoiceHandle;
    @BindView(R.id.activity_control_output_voice_img)
    ImageView outputVoiceImg;
    @BindView(R.id.activity_control_output_voice_handle)
    SeekBar outputVoiceHandle;
    @BindView(R.id.activity_control_cpu_tv)
    TextView cpuTv;
    @BindView(R.id.activity_control_mem_tv)
    TextView menTv;
    @BindView(R.id.activity_controlsurface_one_detele)
    ImageView surfaceOneDelete;
    @BindView(R.id.activity_controlsurface_two_detele)
    ImageView surfaceTwoDelete;
    @BindView(R.id.activity_controlsurface_three_detele)
    ImageView surfaceThreeDelete;
    @BindView(R.id.activity_controlsurface_four_detele)
    ImageView surfaceFourDelete;
    @BindView(R.id.activity_controlsurface_five_detele)
    ImageView surfaceFiveDelete;
    @BindView (R.id.activity_control_indtructor_change_btn)
    Button switchBtn;
    @BindView(R.id.activity_control_output_btn)
    Button outputBtn;
    @BindView (R.id.activity_control_live_btn)
    Button rtmpBtn;
    @BindView (R.id.activity_control_transcribe_btn)
    Button recordBtn;
    @BindView(R.id.activity_control_mode_a)
    TextView modeA;
    @BindView(R.id.activity_control_mode_ab)
    LinearLayout modeAB;
    @BindView(R.id.activity_control_mode_abc)
    LinearLayout modeABC;
    @BindView(R.id.activity_control_mode_abcd)
    LinearLayout modeABCD;
    @BindView(R.id.activity_control_prev_a)
    TextView prevA;
    @BindView(R.id.activity_control_prev_b)
    TextView prevB;
    @BindView(R.id.activity_control_prev_c)
    TextView prevC;
    @BindView(R.id.activity_control_prev_d)
    TextView prevD;
    @BindView(R.id.activity_control_ip_et)
    EditText ipEt;

    private int mPreviewWidth = 1920;
    private int mPreviewHeight = 1080;
    private int mPreviewFps = 25;
    private boolean mPortrait = false;
    private boolean mFront = false;

    FileChooseFragment speedTestFragment;
    List<VideoBean> videoBeanList;
    public static final int CHOOSE_CAMERA = 1;
    public static final int CHOOSE_PHOTO = 2;//REQUEST_CODE
    public static final int REQUEST_CODE = 3;//REQUEST_CODE
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String cpuused = (String) msg.obj;
                    cpuTv.setText(Double.parseDouble(cpuused)*100+"%");
//                    if (cpuused.startsWith(".")){
//                        cpuTv.setText("0"+cpuused+"%");
//                    }
//                    System.out.print("cpuused"+cpuused);

                    break;
                case 2:
                    String menused = (String) msg.obj;
//                    System.out.print("menused"+menused);
                    menTv.setText(menused+"%");
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private ClipDrawable inputclipDrawable = null;
    private ClipDrawable outputclipDrawable = null;
    private MyDialog myDialog = null;
    private String whichClicked = "";
    private int whichClick = -1;
//    private int whichCamera = -1;
    private SurfaceHolder holderLeft = null;
    private SurfaceHolder holderRight = null;
    private Surface surfaceRight = null;
    private SharedPreferences onlive;
    public class CHInfo
    {
        public long ch = 0;
        public SurfaceView view = null;
        public SurfaceHolder holder = null;
        public Surface surface = null;
        public int cameraIndex = -1;
        public Camera camera = null;
        public boolean preview = false;
        public boolean loop = true;
        public boolean video = true;
        public float prevX = 0.0f;
        public float prevY = 0.0f;
        public float prevW = 0.0f;
        public float prevH = 0.0f;
        public float liveX = 0.0f;
        public float liveY = 0.0f;
        public float liveW = 0.0f;
        public float liveH = 0.0f;
        public boolean audio = false;
        public float volume = 1.0f;
    };
    private CHInfo[] chAll = {new CHInfo(), new CHInfo(), new CHInfo(), new CHInfo(), new CHInfo()};
    private CHInfo chMicrophone = new CHInfo();
    private CHInfo chBackMusic = new CHInfo();
    private int videoMode = -1;
    private boolean ch0Select = false;
    private boolean ch1Select = false;
    private boolean ch2Select = false;
    private boolean ch3Select = false;
    private boolean ch4Select = false;
    private Mmixer mMixer = null;
    Intent hdmiSecOutIntent = null;

    private SurfaceHolder.Callback mOneHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
//            Log.d("corelib", ">>>> surface 0 changed.");
        }

        public void surfaceCreated(SurfaceHolder holder) {
            if (chAll[0].cameraIndex >= 0) {
                openCamera(0, chAll[0].cameraIndex);
                initCamera(0);
            }
            chAll[0].surface = holder.getSurface();
//            Log.d("corelib", ">>>> surface 0 created.");
            if ((mMixer!=null) && (chAll[0].ch!=0)) {
                mMixer.chgCh(chAll[0].ch, chAll[0].loop, chAll[0].surface,
                        chAll[0].video, chAll[0].prevX, chAll[0].prevY, chAll[0].prevW, chAll[0].prevH,
                        chAll[0].liveX, chAll[0].liveY, chAll[0].liveW, chAll[0].liveH,
                        chAll[0].audio, chAll[0].volume);
            }
//            Log.d("corelib", ">>>>-- surfaceOne=" + chOne.surface);
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
//            Log.d("corelib", ">>>> surface 0 destroy.");
            if (chAll[0].cameraIndex >= 0) {
                interDestroyCamera(chAll[0].cameraIndex);
            }
            chAll[0].surface = null;
            if ((mMixer!=null) && (chAll[0].ch!=0)) {
                mMixer.chgCh(chAll[0].ch, chAll[0].loop, chAll[0].surface,
                        chAll[0].video, chAll[0].prevX, chAll[0].prevY, chAll[0].prevW, chAll[0].prevH,
                        chAll[0].liveX, chAll[0].liveY, chAll[0].liveW, chAll[0].liveH,
                        chAll[0].audio, chAll[0].volume);

            }
        }
    };
    private SurfaceHolder.Callback mTwoHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        public void surfaceCreated(SurfaceHolder holder) {
            chAll[1].surface = holder.getSurface();
            if ((mMixer!=null) && (chAll[1].ch!=0)) {
                mMixer.chgCh(chAll[1].ch, chAll[1].loop, chAll[1].surface,
                        chAll[1].video, chAll[1].prevX, chAll[1].prevY, chAll[1].prevW, chAll[1].prevH,
                        chAll[1].liveX, chAll[1].liveY, chAll[1].liveW, chAll[1].liveH,
                        chAll[1].audio, chAll[1].volume);
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            chAll[1].surface = null;
            if ((mMixer!=null) && (chAll[1].ch!=0)) {
                mMixer.chgCh(chAll[1].ch, chAll[1].loop, chAll[1].surface,
                        chAll[1].video, chAll[1].prevX, chAll[1].prevY, chAll[1].prevW, chAll[1].prevH,
                        chAll[1].liveX, chAll[1].liveY, chAll[1].liveW, chAll[1].liveH,
                        chAll[1].audio, chAll[1].volume);
            }
        }
    };
    private SurfaceHolder.Callback mThreeHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        public void surfaceCreated(SurfaceHolder holder) {
            chAll[2].surface = holder.getSurface();
            if ((mMixer!=null) && (chAll[2].ch!=0)) {
                mMixer.chgCh(chAll[2].ch, chAll[2].loop, chAll[2].surface,
                        chAll[2].video, chAll[2].prevX, chAll[2].prevY, chAll[2].prevW, chAll[2].prevH,
                        chAll[2].liveX, chAll[2].liveY, chAll[2].liveW, chAll[2].liveH,
                        chAll[2].audio, chAll[2].volume);
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            chAll[2].surface = null;
            if ((mMixer!=null) && (chAll[2].ch!=0)) {
                mMixer.chgCh(chAll[2].ch, chAll[2].loop, chAll[2].surface,
                        chAll[2].video, chAll[2].prevX, chAll[2].prevY, chAll[2].prevW, chAll[2].prevH,
                        chAll[2].liveX, chAll[2].liveY, chAll[2].liveW, chAll[2].liveH,
                        chAll[2].audio, chAll[2].volume);
            }
        }
    };
    private SurfaceHolder.Callback mFourHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        public void surfaceCreated(SurfaceHolder holder) {
            chAll[3].surface = holder.getSurface();
            if ((mMixer!=null) && (chAll[3].ch!=0)) {
                mMixer.chgCh(chAll[3].ch, chAll[3].loop, chAll[3].surface,
                        chAll[3].video, chAll[3].prevX, chAll[3].prevY, chAll[3].prevW, chAll[3].prevH,
                        chAll[3].liveX, chAll[3].liveY, chAll[3].liveW, chAll[3].liveH,
                        chAll[3].audio, chAll[3].volume);
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            chAll[3].surface = null;
            if ((mMixer!=null) && (chAll[3].ch!=0)) {
                mMixer.chgCh(chAll[3].ch, chAll[3].loop, chAll[3].surface,
                        chAll[3].video, chAll[3].prevX, chAll[3].prevY, chAll[3].prevW, chAll[3].prevH,
                        chAll[3].liveX, chAll[3].liveY, chAll[3].liveW, chAll[3].liveH,
                        chAll[3].audio, chAll[3].volume);
            }
        }
    };
    private SurfaceHolder.Callback mFiveHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        public void surfaceCreated(SurfaceHolder holder) {
            chAll[4].surface = holder.getSurface();
            if ((mMixer!=null) && (chAll[4].ch!=0)) {
                mMixer.chgCh(chAll[4].ch, chAll[4].loop, chAll[4].surface,
                        chAll[4].video, chAll[4].prevX, chAll[4].prevY, chAll[4].prevW, chAll[4].prevH,
                        chAll[4].liveX, chAll[4].liveY, chAll[4].liveW, chAll[4].liveH,
                        chAll[4].audio, chAll[4].volume);
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            chAll[4].surface = null;
            if ((mMixer!=null) && (chAll[4].ch!=0)) {
                mMixer.chgCh(chAll[4].ch, chAll[4].loop, chAll[4].surface,
                        chAll[4].video, chAll[4].prevX, chAll[4].prevY, chAll[4].prevW, chAll[4].prevH,
                        chAll[4].liveX, chAll[4].liveY, chAll[4].liveW, chAll[4].liveH,
                        chAll[4].audio, chAll[4].volume);
            }
        }
    };
    private SurfaceHolder.Callback mLeftHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        public void surfaceCreated(SurfaceHolder holder) {
            if (mMixer != null) {
                mMixer.detachPSurface();
                mMixer.attachPSurface(holder.getSurface());
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mMixer != null) {
                mMixer.detachPSurface();
            }
        }
    };
    private SurfaceHolder.Callback mRightHolderCallback = new SurfaceHolder.Callback() {
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        public void surfaceCreated(SurfaceHolder holder) {
            if (mMixer != null) {
                mMixer.detachLSurface();
                surfaceRight = holder.getSurface();
                mMixer.attachLSurface(holder.getSurface());
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mMixer != null) {
                surfaceRight = null;
                mMixer.detachLSurface();
            }
        }
    };
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        if (messageEvent.getCode()==6) {
//            Toast.makeText(this, messageEvent.getMessage(), Toast.LENGTH_SHORT);
//            Uri originalUri = data.getData();
            String strPath = messageEvent.getMessage();
            Log.i(TAG, "onEvent: "+messageEvent.getMessage());
//                    Log.d("corelib", "uri=" + originalUri);
//                    Log.d("corelib", "path=" + strPath);
//                    Log.d("corelib", ">>>> whichClicked=" +whichClicked);

            if (whichClick >= 0)
            {
                chAll[whichClick].ch = mMixer.newCh(strPath, chAll[whichClick].loop, chAll[whichClick].surface,
                        chAll[whichClick].video, chAll[whichClick].prevX, chAll[whichClick].prevY, chAll[whichClick].prevW, chAll[whichClick].prevH,
                        chAll[whichClick].liveX, chAll[whichClick].liveY, chAll[whichClick].liveW, chAll[whichClick].liveH,
                        chAll[whichClick].audio, chAll[whichClick].volume);
            }
//            filechooseEdit.setText(messageEvent.getMessage());
        }
        if (messageEvent.getCode()==2) {
            Toast.makeText(this, messageEvent.getMessage(), Toast.LENGTH_SHORT);
            Log.i("legendqiqi", "onEvent: ControlActivity"+messageEvent.getMessage());
//            editText.setText(messageEvent.getMessage());
        }
    }
    SharedPreferences saveInfo;
    SharedPreferences voice;
    SharedPreferences channel;
    private String intToIp(int paramInt) {
        return (paramInt & 0xFF) + "." + ((paramInt >> 8 & 0xFF)) + "." + ((paramInt >> 16 & 0xFF)) + "."
                + ((paramInt >> 24 & 0xFF));
    }
    private BaseApplication application;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        ButterKnife.bind(this);
        Utils.init(getApplication());
        EventBus.getDefault().register(this);
        application = (BaseApplication) getApplication();
        saveInfo = getSharedPreferences("saveinfo", Context.MODE_PRIVATE);
        channel = getSharedPreferences("channel", Context.MODE_PRIVATE);
        saveInfo.getString("exString","");
        saveInfo.getInt("exInt",0);
        voice = getSharedPreferences("voice",Context.MODE_PRIVATE);
//        String backgroudUrl = voice.getString("backgroudUrl", "");
//        Log.i("legendqiqi", "onCreate: ControlActivity backgroudUrl:"+backgroudUrl);
//        String encode = channel.getString("encode", "");
//        Log.i("legendqiqi", "onCreate: ControlActivity encodeUrl:"+encode);
//        edit.putInt("exInt",1);
//        edit.putString("exString","exString");
        WifiManager my_wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = my_wifiManager.getConnectionInfo();
        onlive = this.getSharedPreferences("onlive", Context.MODE_PRIVATE);
        myDialog = new MyDialog(this);
        EthernetInfo ethernetInfo = new EthernetInfo();
        ethernetInfo.getLocalIpAddress();
        boolean b = MyUtils.hasWifiConnection(this);
        if (b)
            ipEt.setText(intToIp(connectionInfo.getIpAddress()));
        else
            ipEt.setText(ethernetInfo.ipAddress);

        settingtn.setOnClickListener(this);
        outputBtn.setOnClickListener(this);
        surfaceViewOne.setOnClickListener(this);
        surfaceViewTwo.setOnClickListener(this);
        surfaceViewThree.setOnClickListener(this);
        surfaceViewFour.setOnClickListener(this);
        surfaceViewFive.setOnClickListener(this);
        surfaceOneDelete.setOnClickListener(this);
        surfaceTwoDelete.setOnClickListener(this);
        surfaceThreeDelete.setOnClickListener(this);
        surfaceFourDelete.setOnClickListener(this);
        surfaceFiveDelete.setOnClickListener(this);
        switchBtn.setOnClickListener(this);
        rtmpBtn.setOnClickListener(this);
        recordBtn.setOnClickListener(this);
        modeA.setOnClickListener(this);
        modeAB.setOnClickListener(this);
        modeABC.setOnClickListener(this);
        modeABCD.setOnClickListener(this);
        prevA.setOnClickListener(this);
        prevB.setOnClickListener(this);
        prevC.setOnClickListener(this);
        prevD.setOnClickListener(this);
        inputclipDrawable = (ClipDrawable) inputVoiceImg.getDrawable();
        inputclipDrawable.setLevel(3000);
        outputclipDrawable = (ClipDrawable) outputVoiceImg.getDrawable();
        outputclipDrawable.setLevel(3000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                    Message message = handler.obtainMessage();
                    message.what=1;
//                    DecimalFormat df = new DecimalFormat("#0.00");
                        String cpuRateDesc = getCPURateDesc().split(":")[1];
                        message.obj=cpuRateDesc;
                    Log.i("legendqi",cpuRateDesc);
                    handler.sendMessage(message);
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Message message = handler.obtainMessage();
                        message.what=2;
                        long totalMemory = getTotalMemory();
                        DecimalFormat df = new DecimalFormat("#.00");
//                        String.format("%.2f", f)
                        double f = ((totalMemory - getAvailMemory()) / (float)totalMemory)*100;
//                        System.out.println("legend men:  "+f);
                        String format = df.format(f);
                        message.obj=format;
                        handler.sendMessage(message);
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        chMicrophone.video = false;
        chMicrophone.audio = true;
        chMicrophone.volume = 1.0f;
        chBackMusic.video = false;
        chBackMusic.audio = true;
        chBackMusic.volume = 1.0f;

        inputVoiceHandle.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int max = seekBar.getMax();
                double scale = (double)progress/(double)max;
//                ClipDrawable drawable = (ClipDrawable) inputVoiceImg.getBackground();
                inputclipDrawable.setLevel((int) (10000*scale));
//                Log.d("corelib", ">>>> progress=" + progress);
                chMicrophone.volume = ((float)progress) / 50;
//                Log.d("corelib", ">>>> volume=" + chMicrophone.volume);
                if (mMixer != null) {
                    mMixer.chgCh(chMicrophone.ch, chMicrophone.loop, chMicrophone.surface,
                            chMicrophone.video, chMicrophone.prevX, chMicrophone.prevY, chMicrophone.prevW, chMicrophone.prevH,
                            chMicrophone.liveX, chMicrophone.liveY, chMicrophone.liveW, chMicrophone.liveH,
                            chMicrophone.audio, chMicrophone.volume);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        outputVoiceHandle.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int max = seekBar.getMax();
                float volume = 1.0f;
                double scale = (double)progress/(double)max;
//                ClipDrawable drawable = (ClipDrawable) outputVoiceImg.getBackground();
                outputclipDrawable.setLevel((int) (10000*scale));

                volume = ((float)progress) / 50;
                if (mMixer != null)
                {
                    mMixer.setLVolume(volume);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        surfaceViewOne.setZOrderOnTop(true);
        surfaceViewTwo.setZOrderOnTop(true);
        surfaceViewThree.setZOrderOnTop(true);
        surfaceViewFour.setZOrderOnTop(true);
        surfaceViewFive.setZOrderOnTop(true);
        holderLeft = surfaceViewLeft.getHolder();
        surfaceViewLeft.setZOrderOnTop(true);
        holderRight = surfaceViewRight.getHolder();
        surfaceViewRight.setZOrderOnTop(true);

        chAll[0].view = surfaceViewOne;
        chAll[0].holder = chAll[0].view.getHolder();
        chAll[0].holder.addCallback(mOneHolderCallback);
        chAll[1].view = surfaceViewTwo;
        chAll[1].holder = chAll[1].view.getHolder();
        chAll[1].holder.addCallback(mTwoHolderCallback);
        chAll[2].view = surfaceViewThree;
        chAll[2].holder = chAll[2].view.getHolder();
        chAll[2].holder.addCallback(mThreeHolderCallback);
        chAll[3].view = surfaceViewFour;
        chAll[3].holder = chAll[3].view.getHolder();
        chAll[3].holder.addCallback(mFourHolderCallback);
        chAll[4].view = surfaceViewFive;
        chAll[4].holder = chAll[4].view.getHolder();
        chAll[4].holder.addCallback(mFiveHolderCallback);
        holderLeft.addCallback(mLeftHolderCallback);
        holderRight.addCallback(mRightHolderCallback);
        mMixer = new Mmixer();
        if (mMixer != null)
        {
            String backgroudUrl = voice.getString("backgroudUrl", "");

            mMixer.init();
            chMicrophone.ch = mMixer.newMicrophoneCh("microphone", chMicrophone.loop, chMicrophone.surface, chMicrophone.video,
                    chMicrophone.prevX, chMicrophone.prevY, chMicrophone.prevW, chMicrophone.prevH,
                    chMicrophone.liveX, chMicrophone.liveY, chMicrophone.liveW, chMicrophone.liveH,
                    chMicrophone.audio, chMicrophone.volume);
//            if (backgroudUrl.length() > 0)
//            {
//                chBackMusic.ch = mMixer.newCh(backgroudUrl, chBackMusic.loop, chBackMusic.surface, chBackMusic.video,
//                        chBackMusic.prevX, chBackMusic.prevY, chBackMusic.prevW, chBackMusic.prevH,
//                        chBackMusic.liveX, chBackMusic.liveY, chBackMusic.liveW, chBackMusic.liveH,
//                        chBackMusic.audio, chBackMusic.volume);
//            }
            mMixer.startVPrev();
            mMixer.startVLive();
            mMixer.startNMix();
        }
        application.setmMixer(mMixer);
        application.setInfo(chAll);

        if (Build.VERSION.SDK_INT >= 23) {
			  if(!Settings.canDrawOverlays(getApplicationContext())) {
				//启动Activity让用户授权
				Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
				startActivity(intent);
			}
		}
        hdmiSecOutIntent = new Intent(this,HdmiSecService.class);
        startService(hdmiSecOutIntent);
    }

    private boolean isServiceRunning(){
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (HdmiSecService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy()
    {
        EventBus.getDefault().unregister(this);
        //退出时储存相关信息
        SharedPreferences.Editor edit = saveInfo.edit();
        //存int
        edit.putInt("exInt",1);
        //存String
        edit.putString("exString","exString");
        edit.commit();
        EventBus.getDefault().unregister(this);

        if(isServiceRunning()) {
//            Intent broadCastIntent = new Intent();
//            broadCastIntent.setAction("android.set");
//            broadCastIntent.putExtra("paramInt", 0);
//            sendBroadcast(broadCastIntent);

            stopService(hdmiSecOutIntent);
        }
        if ((chAll[0].cameraIndex) >= 0)
        {
            destroyCamera(0);
        }
        if ((chAll[1].cameraIndex) >= 0)
        {
            destroyCamera(1);
        }
        if ((chAll[2].cameraIndex) >= 0)
        {
            destroyCamera(2);
        }
        if ((chAll[3].cameraIndex) >= 0)
        {
            destroyCamera(3);
        }
        if ((chAll[4].cameraIndex) >= 0)
        {
            destroyCamera(4);
        }
        if (mMixer != null)
        {
            mMixer.stopRec();
            mMixer.stopRtmp();
            mMixer.stopRMix();
            mMixer.stopNMix();
            mMixer.stopVLive();
            mMixer.stopVPrev();
            mMixer.destroy();
            mMixer = null;
        }

        super.onDestroy();
    }

    private int videoChReset(int ch)
    {
        if ((chAll[ch].cameraIndex) >= 0)
        {
            destroyCamera(ch);
        }
        if (chAll[ch].ch != 0) {
            if (mMixer != null) {
                mMixer.delCh(chAll[ch].ch);
            }

            chAll[ch].view.setVisibility(View.GONE);
            chAll[ch].view.setVisibility((View.VISIBLE));
        }
        chAll[ch].ch = 0;
        chAll[ch].loop = true;
        chAll[ch].video = true;
        chAll[ch].prevX = 0.0f;
        chAll[ch].prevY = 0.0f;
        chAll[ch].prevW = 0.0f;
        chAll[ch].prevH = 0.0f;
        chAll[ch].liveX = 0.0f;
        chAll[ch].liveY = 0.0f;
        chAll[ch].liveW = 0.0f;
        chAll[ch].liveH = 0.0f;
        chAll[ch].audio = false;
        chAll[ch].volume = 1.0f;

        return 0;
    }
    private int videoModeReset() {
        for (int i=0; i<5; i++) {
            chAll[i].prevX = chAll[i].prevY = chAll[i].prevW = chAll[i].prevH = 0.0f;
//            chAll[i].liveX = chAll[i].liveY = chAll[i].liveW = chAll[i].liveH = 0.0f;
        }

        ch0Select = false;
        prevA.setBackgroundColor(0xffffffff);
        ch1Select = false;
        prevB.setBackgroundColor(0xffffffff);
        ch2Select = false;
        prevC.setBackgroundColor(0xffffffff);
        ch3Select = false;
        prevD.setBackgroundColor(0xffffffff);

        return 0;
    }
    private int videoModeSelect(int mode, int i_cur)
    {
        if (mode == 0) {
            if (i_cur != 0)
            {
                ch0Select = false;
                prevA.setBackgroundColor(0xffffffff);
            }
            if (i_cur != 1)
            {
                ch1Select = false;
                prevB.setBackgroundColor(0xffffffff);
            }
            if (i_cur != 2)
            {
                ch2Select = false;
                prevC.setBackgroundColor(0xffffffff);
            }
            if (i_cur != 3) {
                ch3Select = false;
                prevD.setBackgroundColor(0xffffffff);
            }
        }
        else if (mode == 1) {
            int i_total = 1;

            if (i_cur != 0)
            {
                if (ch0Select)
                {
                    i_total++;
                }
                if (i_total > 2) {
                    ch0Select = false;
                    prevA.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 1)
            {
                if (ch1Select)
                {
                    i_total++;
                }
                if (i_total > 2) {
                    ch1Select = false;
                    prevB.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 2)
            {
                if (ch2Select)
                {
                    i_total++;
                }
                if (i_total > 2) {
                    ch2Select = false;
                    prevC.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 3) {
                if (ch3Select)
                {
                    i_total++;
                }
                if (i_total > 2) {
                    ch3Select = false;
                    prevD.setBackgroundColor(0xffffffff);
                }
            }
        }
        if (mode == 2) {
            int i_total = 1;

            if (i_cur != 0)
            {
                if (ch0Select)
                {
                    i_total++;
                }
                if (i_total > 3) {
                    ch0Select = false;
                    prevA.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 1)
            {
                if (ch1Select)
                {
                    i_total++;
                }
                if (i_total > 3) {
                    ch1Select = false;
                    prevB.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 2)
            {
                if (ch2Select)
                {
                    i_total++;
                }
                if (i_total > 3) {
                    ch2Select = false;
                    prevC.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 3) {
                if (ch3Select)
                {
                    i_total++;
                }
                if (i_total > 3) {
                    ch3Select = false;
                    prevD.setBackgroundColor(0xffffffff);
                }
            }
        }
        if (mode == 3) {
            int i_total = 1;

            if (i_cur != 0)
            {
                if (ch0Select)
                {
                    i_total++;
                }
                if (i_total > 4) {
                    ch0Select = false;
                    prevA.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 1)
            {
                if (ch1Select)
                {
                    i_total++;
                }
                if (i_total > 4) {
                    ch1Select = false;
                    prevB.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 2)
            {
                if (ch2Select)
                {
                    i_total++;
                }
                if (i_total > 4) {
                    ch2Select = false;
                    prevC.setBackgroundColor(0xffffffff);
                }
            }
            if (i_cur != 3) {
                if (ch3Select)
                {
                    i_total++;
                }
                if (i_total > 4) {
                    ch3Select = false;
                    prevD.setBackgroundColor(0xffffffff);
                }
            }
        }

        return 0;
    }
    private int videoModeSet(int mode)
    {
        if (mode < 0){
            return -1;
        }

        int i_ch = 0;
        int[] i_chSelect = {-1, -1, -1, -1, -1};
        if (ch0Select) {
            i_chSelect[i_ch] = 0;
            i_ch++;
        }
        else
        {
            chAll[0].prevX = chAll[0].prevY = chAll[0].prevW = chAll[0].prevH = 0.0f;
//            chAll[0].liveX = chAll[0].liveY = chAll[0].liveW = chAll[0].liveH = 0.0f;
        }
        if (ch1Select) {
            i_chSelect[i_ch] = 1;
            i_ch++;
        }
        else
        {
            chAll[1].prevX = chAll[1].prevY = chAll[1].prevW = chAll[1].prevH = 0.0f;
//            chAll[1].liveX = chAll[1].liveY = chAll[1].liveW = chAll[1].liveH = 0.0f;
        }
        if (ch2Select) {
            i_chSelect[i_ch] = 2;
            i_ch++;
        }
        else
        {
            chAll[2].prevX = chAll[2].prevY = chAll[2].prevW = chAll[2].prevH = 0.0f;
//            chAll[2].liveX = chAll[2].liveY = chAll[2].liveW = chAll[2].liveH = 0.0f;
        }
        if (ch3Select) {
            i_chSelect[i_ch] = 3;
            i_ch++;
        }
        else
        {
            chAll[3].prevX = chAll[3].prevY = chAll[3].prevW = chAll[3].prevH = 0.0f;
//            chAll[3].liveX = chAll[3].liveY = chAll[3].liveW = chAll[3].liveH = 0.0f;
        }
        if (ch4Select) {
            i_chSelect[i_ch] = 4;
            i_ch++;
        }
        else
        {
            chAll[4].prevX = chAll[4].prevY = chAll[4].prevW = chAll[4].prevH = 0.0f;
//            chAll[4].liveX = chAll[4].liveY = chAll[4].liveW = chAll[4].liveH = 0.0f;
        }

        if (mode == 0) {
            if (i_chSelect[0] >= 0) {
                int i_tmp = i_chSelect[0];
                chAll[i_tmp].prevX = 0.0f;
                chAll[i_tmp].prevY = 0.0f;
                chAll[i_tmp].prevW = 1.0f;
                chAll[i_tmp].prevH = 1.0f;
                Log.d("corelib", ">>>> mode 0, " + i_tmp + " " + chAll[i_tmp].prevX + " " + chAll[i_tmp].prevY + " "+ chAll[i_tmp].prevW + " "+ chAll[i_tmp].prevH );
            }
        }
        else if (mode == 1) {
            Log.d("corelib", ">>>> ch0=" + i_chSelect[0] + " ch1=" + i_chSelect[1]);
            if (i_chSelect[0] >= 0) {
                int i_tmp = i_chSelect[0];
                chAll[i_tmp].prevX = 0.0f;
                chAll[i_tmp].prevY = 0.25f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
                Log.d("corelib", ">>>> mode 1 left, " + i_tmp + " " + chAll[i_tmp].prevX + " " + chAll[i_tmp].prevY + " "+ chAll[i_tmp].prevW + " "+ chAll[i_tmp].prevH );
            }
            if (i_chSelect[1] >= 0) {
                int i_tmp = i_chSelect[1];
                chAll[i_tmp].prevX = 0.5f;
                chAll[i_tmp].prevY = 0.25f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
                Log.d("corelib", ">>>> mode 1 right, " + i_tmp + " " + chAll[i_tmp].prevX + " " + chAll[i_tmp].prevY + " "+ chAll[i_tmp].prevW + " "+ chAll[i_tmp].prevH );
            }
        }
        else if (mode == 2) {
            if (i_chSelect[0] >= 0) {
                int i_tmp = i_chSelect[0];
                chAll[i_tmp].prevX = 0.0f;
                chAll[i_tmp].prevY = 0.25f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
            if (i_chSelect[1] >= 0) {
                int i_tmp = i_chSelect[1];
                chAll[i_tmp].prevX = 0.5f;
                chAll[i_tmp].prevY = 0.0f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
            if (i_chSelect[2] >= 0) {
                int i_tmp = i_chSelect[2];
                chAll[i_tmp].prevX = 0.5f;
                chAll[i_tmp].prevY = 0.5f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
        }
        else if (mode == 3) {
            if (i_chSelect[0] >= 0) {
                int i_tmp = i_chSelect[0];
                chAll[i_tmp].prevX = 0.0f;
                chAll[i_tmp].prevY = 0.0f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
            if (i_chSelect[1] >= 0) {
                int i_tmp = i_chSelect[1];
                chAll[i_tmp].prevX = 0.5f;
                chAll[i_tmp].prevY = 0.0f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
            if (i_chSelect[2] >= 0) {
                int i_tmp = i_chSelect[2];
                chAll[i_tmp].prevX = 0.0f;
                chAll[i_tmp].prevY = 0.5f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
            if (i_chSelect[3] >= 0) {
                int i_tmp = i_chSelect[3];
                chAll[i_tmp].prevX = 0.5f;
                chAll[i_tmp].prevY = 0.5f;
                chAll[i_tmp].prevW = 0.5f;
                chAll[i_tmp].prevH = 0.5f;
            }
        }

        return 0;
    }
    private int videoModeUse()
    {
        for (int i=0; i<5; i++)
        {
//            Log.d("corelib", ">>>> " + i + " ch=" + chAll[i].ch + " video=" + chAll[i].video + " prevW="+chAll[i].prevW + " prevH=" + chAll[i].prevH);
            mMixer.chgCh(chAll[i].ch, chAll[i].loop, chAll[i].surface,
                    chAll[i].video, chAll[i].prevX, chAll[i].prevY, chAll[i].prevW, chAll[i].prevH,
                    chAll[i].liveX, chAll[i].liveY, chAll[i].liveW, chAll[i].liveH,
                    chAll[i].audio, chAll[i].volume);
        }

        return 0;
    }
    private int videoModeSwitchToLive()
    {
        for (int i=0; i<5; i++)
        {
            if ((mMixer!=null) && (chAll[i].ch!=0)) {
                chAll[i].liveX = chAll[i].prevX;
                chAll[i].liveY = chAll[i].prevY;
                chAll[i].liveW = chAll[i].prevW;
                chAll[i].liveH = chAll[i].prevH;
                if ((chAll[i].liveW>0) && (chAll[i].liveW>0)) {
                    chAll[i].audio = true;
                }
                else
                {
                    chAll[i].audio = false;
                }
                mMixer.chgCh(chAll[i].ch, chAll[i].loop, chAll[i].surface,
                        chAll[i].video, chAll[i].prevX, chAll[i].prevY, chAll[i].prevW, chAll[i].prevH,
                        chAll[i].liveX, chAll[i].liveY, chAll[i].liveW, chAll[i].liveH,
                        chAll[i].audio, chAll[i].volume);
            }
        }

        return 0;
    }

    public int restoreLiveSurface() {
        if (mMixer != null) {
            mMixer.detachLSurface();
            if (surfaceRight != null) {
                Log.d("corelib", ">>>> restore surface right.");
                mMixer.attachLSurface(surfaceRight);
            }
        }

        return 0;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.activity_control_setting_btn:
                startActivity(new Intent(this,SettingActivity.class));
                break;
            case R.id.activity_controlsurface_one:
                whichClicked="surfaceOne";
                whichClick = 0;
                showDialog();
                break;
            case R.id.activity_controlsurface_two:
                whichClicked="surfaceTwo";
                whichClick = 1;
                showDialog();
                break;
            case R.id.activity_controlsurface_three:
                whichClicked="surfaceThree";
                whichClick = 2;
                showDialog();
                break;
            case R.id.activity_controlsurface_four:
                whichClicked="surfaceFour";
                whichClick = 3;
                showDialog();
                break;
            case R.id.activity_controlsurface_five:
                whichClicked="surfaceFive";
                whichClick = 4;
                showDialog();
                break;
            case R.id.activity_controlsurface_one_detele:
                ToastUtils.showShort("clear one");
                videoChReset(0);
            break;
            case R.id.activity_controlsurface_two_detele:
                ToastUtils.showShort("clear two");
                videoChReset(1);
                break;
            case R.id.activity_controlsurface_three_detele:
                ToastUtils.showShort("clear three");
                videoChReset(2);
                break;
            case R.id.activity_controlsurface_four_detele:
                ToastUtils.showShort("clear four");
                videoChReset(3);
                break;
            case R.id.activity_controlsurface_five_detele:
                ToastUtils.showShort("clear five");
                videoChReset(4);
                break;
            case R.id.activity_control_mode_a:
                videoMode = 0;
                modeA.setBackgroundColor(0xff00ff00);
                modeAB.setBackgroundColor(0xffffffff);
                modeABC.setBackgroundColor(0xffffffff);
                modeABCD.setBackgroundColor(0xffffffff);
                videoModeReset();
                break;
            case R.id.activity_control_mode_ab:
                videoMode = 1;
                modeA.setBackgroundColor(0xffffffff);
                modeAB.setBackgroundColor(0xff00ff00);
                modeABC.setBackgroundColor(0xffffffff);
                modeABCD.setBackgroundColor(0xffffffff);
                videoModeReset();
                break;
            case R.id.activity_control_mode_abc:
                videoMode = 2;
                modeA.setBackgroundColor(0xffffffff);
                modeAB.setBackgroundColor(0xffffffff);
                modeABC.setBackgroundColor(0xff00ff00);
                modeABCD.setBackgroundColor(0xffffffff);
                videoModeReset();
                break;
            case R.id.activity_control_mode_abcd:
                videoMode = 3;
                modeA.setBackgroundColor(0xffffffff);
                modeAB.setBackgroundColor(0xffffffff);
                modeABC.setBackgroundColor(0xffffffff);
                modeABCD.setBackgroundColor(0xff00ff00);
                videoModeReset();
                break;
            case R.id.activity_control_prev_a:
                if (!ch0Select) {
                    ch0Select = true;
                    prevA.setBackgroundColor(0xff00ff00);
                    videoModeSelect(videoMode, 0);
                }
                else {
                    ch0Select = false;
                    prevA.setBackgroundColor(0xffffffff);
                }
                videoModeSet(videoMode);
                videoModeUse();
                break;
            case R.id.activity_control_prev_b:
                if (!ch1Select) {
                    ch1Select = true;
                    prevB.setBackgroundColor(0xff00ff00);
                    videoModeSelect(videoMode, 1);
                }
                else {
                    ch1Select = false;
                    prevB.setBackgroundColor(0xffffffff);
                }
                videoModeSet(videoMode);
                videoModeUse();
                break;
            case R.id.activity_control_prev_c:
                if (!ch2Select) {
                    ch2Select = true;
                    prevC.setBackgroundColor(0xff00ff00);
                    videoModeSelect(videoMode, 2);
                }
                else {
                    ch2Select = false;
                    prevC.setBackgroundColor(0xffffffff);
                }
                videoModeSet(videoMode);
                videoModeUse();
                break;
            case R.id.activity_control_prev_d:
                if (!ch3Select) {
                    ch3Select = true;
                    prevD.setBackgroundColor(0xff00ff00);
                    videoModeSelect(videoMode, 3);
                }
                else
                {
                    ch3Select = false;
                    prevD.setBackgroundColor(0xffffffff);
                }
                videoModeSet(videoMode);
                videoModeUse();
                break;

            case R.id.activity_control_indtructor_change_btn:
                videoModeSwitchToLive();
                break;
            //外部输出
            case R.id.activity_control_output_btn:
                String state = FileIOUtils.readFile2String("/sys/devices/virtual/switch/hdmi/state");

                if (isServiceRunning() && state.equals("1")){
                    String strText = outputBtn.getText().toString();
                    if (strText.compareTo("外部输出") == 0) {
                        Intent broadCastIntent = new Intent();
                        broadCastIntent.setAction("android.set");
                        broadCastIntent.putExtra("paramInt", 1);
                        sendBroadcast(broadCastIntent);

                        outputBtn.setText("停止");
                    }
                    else
                    {
                        Intent broadCastIntent = new Intent();
                        broadCastIntent.setAction("android.set");
                        broadCastIntent.putExtra("paramInt", 0);
                        sendBroadcast(broadCastIntent);

                        outputBtn.setText("外部输出");
                    }
                }else{
                    Toast.makeText(this,"异显服务未开启/未接显示器",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.activity_control_live_btn:
                if (mMixer != null)
                {
                    String strText = rtmpBtn.getText().toString();
                    if (strText.compareTo("直播") == 0)
                    {
                        String rtmp = onlive.getString("rtmp", "");
                        Log.i(TAG, "onClick: "+rtmp);
                        if (TextUtils.isEmpty(rtmp)){
                            Toast.makeText(this,"请在设置中设置RTMP地址",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mMixer.startRtmp(rtmp);//rtmp://42.51.33.213/live/test224
                        rtmpBtn.setText("停止直播");
                    }
                    else
                    {
                        mMixer.stopRtmp();
                        rtmpBtn.setText("直播");
                    }
                }
                break;
            case R.id.activity_control_transcribe_btn:
                if (mMixer != null) {
                    String strText = recordBtn.getText().toString();
                    if (strText.compareTo("录制") == 0) {
                        mMixer.startRec("/mnt/sdcard/record.mp4");
                        recordBtn.setText("停止录制");
                    } else {
                        mMixer.stopRec();
                        recordBtn.setText("录制");
                    }
                }
                break;
        }
    }
    public void showDialog(){

        myDialog.show();
//        myDialog.setWindowAlpa(true);
        myDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
//                myDialog.setWindowAlpa(false);
            }
        });
        //直播
        myDialog.set_paizhao_OnclickListener(new MyDialog.onPaizhao_OnclickListener() {
            @Override
            public void paizhao_onClick() {
                myDialog.dismiss();
                requestContactPermission(CHOOSE_CAMERA);
            }
        });
        myDialog.set_internet_OnclickListener(new MyDialog.onInternet_OnclickListener() {
            @Override
            public void internet_onClick() {
                String strUrl = channel.getString("encode", "");
//                Log.i("legendqiqi", "onCreate: ControlActivity encodeUrl:"+strUrl);

                myDialog.dismiss();
                if ((whichClick>=0) && (strUrl.length()>0))
                {
                    chAll[whichClick].ch = mMixer.newCh(strUrl, chAll[whichClick].loop, chAll[whichClick].surface,
                            chAll[whichClick].video, chAll[whichClick].prevX, chAll[whichClick].prevY, chAll[whichClick].prevW, chAll[whichClick].prevH,
                            chAll[whichClick].liveX, chAll[whichClick].liveY, chAll[whichClick].liveW, chAll[whichClick].liveH,
                            chAll[whichClick].audio, chAll[whichClick].volume);
                }
            }
        });
        //相册
        myDialog.set_xiangce_OnclickListener(new MyDialog.onXiangce_OnclickListener() {
            @Override
            public void xiangce_onClick() {
                myDialog.dismiss();
                Toast.makeText(ControlActivity.this,"TODO",Toast.LENGTH_LONG).show();
//                Toast.makeText(MainActivity.this,"相册",Toast.LENGTH_SHORT).show(); ACTION_GET_CONTENT
//                requestContactPermission(CHOOSE_PHOTO);
//                Intent intent = new Intent();
////                Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                intent.setType("image/*");
//                intent.setAction(Intent.ACTION_GET_CONTENT);
//                startActivityForResult(intent, CHOOSE_PHOTO);
            }
        });
        myDialog.set_video_OnclickListener(new MyDialog.onVideo_OnclickListener() {
            @Override
            public void video_onClick() {
                myDialog.dismiss();
//                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, REQUEST_CODE);
                videoBeanList = MyUtils.queryLocalVideo(getApplicationContext(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,0);
                final FileChooseAdapater adapater = new FileChooseAdapater(getApplicationContext(),videoBeanList);
                FileChooseFragment speedTestFragment = new FileChooseFragment();
                speedTestFragment.setAdapater(adapater);
                speedTestFragment.show(getSupportFragmentManager(),"home_filechose");
            }
        });
    }

    private Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            int i = 0;
            for (i=0; i<5; i++)
            {
                if ((chAll[i].camera!=null) && (chAll[i].camera==camera)) {
                    break;
                }
            }

//            Log.d("corelib", ">>>> i=" + i + " camera=" + camera + " 0=" + chAll[0].camera);
//            Log.d("corelib", "- " +  System.currentTimeMillis());
            // 传递进来的data,默认是YUV420SP的
           if ((i>=0) && (i<5) && (chAll[i].ch != 0)) {
               mMixer.inputCh(chAll[i].ch, data);
            }
        }
    };
    private int initCamera(int chIndex)
    {
        if (chAll[chIndex].camera != null) {
            if (chAll[chIndex].preview) {
                chAll[chIndex].camera.stopPreview();
            }

            try {
				/* Camera Service settings */
                Camera.Parameters parameters = chAll[chIndex].camera.getParameters();
                // parameters.setFlashMode("off"); // 无闪光灯
                //这里必须使用yuv 420 sp格式 否则和NDK不匹配！！！
                parameters.setPreviewFormat(PixelFormat.YCbCr_420_SP); // Sets

                // 【调试】获取caera支持的PictrueSize，看看能否设置？？
                List<Size> previewSizes = chAll[chIndex].camera.getParameters()
                        .getSupportedPreviewSizes();
                List<Integer> previewFormats = chAll[chIndex].camera.getParameters()
                        .getSupportedPreviewFormats();
                List<Integer> previewFrameRates = chAll[chIndex].camera.getParameters()
                        .getSupportedPreviewFrameRates();
                Log.i(TAG + "initCamera", "cyy support parameters is ");
                Size psize = null;
                //下面列出摄像头支持的所有格式
                for (int i = 0; i < previewSizes.size(); i++) {
                    psize = previewSizes.get(i);
                    Log.i(TAG + "initCamera", "PreviewSize,width: "
                            + psize.width + " height" + psize.height);
                }
                Integer pf = null;
                for (int i = 0; i < previewFormats.size(); i++) {
                    pf = previewFormats.get(i);
                    Log.i(TAG + "initCamera", "previewformates:" + pf);
                    //Toast.makeText(this, "previewformates:"+pf, Toast.LENGTH_LONG).show();
                    break;
                }
                for (int i=0; i<previewFrameRates.size(); i++) {
                    pf = previewFrameRates.get(i);
                    Log.i(TAG, "previewFrameRates: " + pf);
                }

                // 设置拍照和预览图片大小
                //parameters.setPictureSize(mPreviewWidth, mPreviewHeight); // 指定拍照图片的大小
                parameters.setPreviewSize(mPreviewWidth, mPreviewHeight); // 指定preview的大小
                // 设置帧率
                parameters.setPreviewFrameRate(mPreviewFps);
                // 这两个属性 如果这两个属性设置的和真实手机的不一样时，就会报错

                // 横竖屏镜头自动调整
                if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
                {
                    parameters.set("orientation", "portrait");
                    parameters.set("rotation", 90); // 镜头角度转90度（默认摄像头是横拍）
                    chAll[chIndex].camera.setDisplayOrientation(90); // 在2.2以上可以使用
                    mPortrait = true;
                }
                else // 如果是横屏
                {
                    parameters.set("orientation", "landscape"); //
                    chAll[chIndex].camera.setDisplayOrientation(0); // 在2.2以上可以使用
                }

                // 设定配置参数并开启预览
                chAll[chIndex].camera.setParameters(parameters); // 将Camera.Parameters设定予Camera
                chAll[chIndex].camera.startPreview(); // 打开预览画面
                chAll[chIndex].preview = true;

                //列出预览支持的分辨率，帧率，颜色格式
                Camera.Size csize = chAll[chIndex].camera.getParameters().getPreviewSize();
                mPreviewHeight = csize.height; //
                mPreviewWidth = csize.width;
                Log.i(TAG + "initCamera", "after setting, previewSize:width: "
                        + csize.width + " height: " + csize.height);
                csize = chAll[chIndex].camera.getParameters().getPictureSize();
                Log.i(TAG + "initCamera", "after setting, pictruesize:width: "
                        + csize.width + " height: " + csize.height);
                Log.i(TAG + "initCamera", "after setting, previewformate is "
                        + chAll[chIndex].camera.getParameters().getPreviewFormat());
                Log.i(TAG + "initCamera", "after setting, previewframetate is "
                        + chAll[chIndex].camera.getParameters().getPreviewFrameRate());

                //20140113 调整宽度高度比!
//                int dw = getWindowManager().getDefaultDisplay().getWidth();
//                int dh = getWindowManager().getDefaultDisplay().getHeight();
//                //Log.d("corelib", "dw="+dw+" dh="+dh);
//                // calculate aspect ratio
//                double ar = 0.0;
//                double dar = 0.0;
//                if (!mPortrait)
//                    ar = (double)mPreviewWidth / (double)mPreviewHeight;
//                else
//                    ar = (double)mPreviewHeight / (double)mPreviewWidth;
//                // calculate display aspect ratio
//                dar = (double) dw / (double) dh;
//                if (dar < ar)
//                    dh = (int) (dw / ar);
//                else
//                    dw = (int) (dh * ar);
//
//                holderOne.setFixedSize(mPreviewWidth, mPreviewHeight); //注意这一句话！！！ 20150107！！！
//                ViewGroup.LayoutParams lp = surfaceViewOne.getLayoutParams();
//                //Log.d("corelib", "lp.width="+lp.width+ " lp.height="+lp.height);
//                lp.width = dw;
//                lp.height = dh;
//                surfaceViewOne.setLayoutParams(lp);
                chAll[chIndex].camera.setPreviewCallback(mPreviewCallback);
            } catch (Exception e) {
                Toast.makeText(this, "无法以" + mPreviewWidth+ "x" + mPreviewHeight + " NV21 " + mPreviewFps + "帧格式预览摄像头，此演示无法工作！！！", Toast.LENGTH_LONG).show();
                e.printStackTrace();

                return -1;
            }
        }

        return 0;
    }
    private int openCamera(int chIndex, int cameraIndex)
    {
        if ((Build.VERSION.SDK_INT) >= 9)
        {
            if (Camera.getNumberOfCameras() > 1) {
                chAll[chIndex].camera = Camera.open(cameraIndex);
            }
            else {
                chAll[chIndex].camera = Camera.open(0);
            }
        }
        else {
            return -1;
        }
        try {
            Log.i(TAG, "SurfaceHolder.Callback：surface Created mCamera=" + chAll[chIndex].camera);
            chAll[chIndex].camera.setPreviewDisplay(chAll[whichClick].holder);// set the surface to be
            // used for live preview
        } catch (Exception ex) {
            if (chAll[chIndex].camera != null) {
                chAll[chIndex].camera.release();
                chAll[chIndex].camera = null;
            }
            Log.i(TAG, ex.getMessage());
        }

        return 0;
    }
    private int interDestroyCamera(int chIndex)
    {
        if (chAll[chIndex].camera != null) {
            chAll[chIndex].camera.setPreviewCallback(null); // ！！这个必须在前，不然退出出错
            chAll[chIndex].camera.stopPreview();
            chAll[chIndex].camera.release();
            chAll[chIndex].camera = null;
            chAll[chIndex].preview = false;
        }

        return 0;
    }
    private int destroyCamera(int chIndex)
    {
        if (chAll[chIndex].camera != null) {
            chAll[chIndex].camera.setPreviewCallback(null); // ！！这个必须在前，不然退出出错
            chAll[chIndex].camera.stopPreview();
            chAll[chIndex].camera.release();
            chAll[chIndex].camera = null;
            chAll[chIndex].preview = false;
            chAll[chIndex].cameraIndex = -1;
        }

        return 0;
    }
    private int findCameraIndex() {
        int cameras = 0;
        int index = -1;
        if ((Build.VERSION.SDK_INT) >= 9) {
            cameras = Camera.getNumberOfCameras();
        }

        Log.d("corelib", ">>>> cameras=" + cameras);
        for (int i=0; i<cameras; i++)
        {
            int j = 0;
            for (j=0; j<5; j++)
            {
                if (chAll[j].cameraIndex == i) {
                    break;
                }
            }
            if (j >= 5)
            {
                index = i;
                break;
            }
        }

        return index;
    }
    private void requestContactPermission(int requestCode) {
        if (CHOOSE_PHOTO == requestCode && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请 WRITE_CONTACTS 权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    CHOOSE_PHOTO);
        } else if (CHOOSE_CAMERA == requestCode && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    CHOOSE_CAMERA);
        } else {
            if (requestCode == CHOOSE_PHOTO) {
//                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(intent, requestCode);
            } else if (requestCode == CHOOSE_CAMERA) {
                if (whichClick >= 0) {
                    int cameraIndex = findCameraIndex();
//                    Log.d("corelib", ">>>> cameraIndex=" + cameraIndex);
                    if (cameraIndex >= 0) {
                        chAll[whichClick].ch = mMixer.newCameraCh("camera", chAll[whichClick].loop, chAll[whichClick].surface,
                                chAll[whichClick].video, mPreviewWidth, mPreviewHeight, chAll[whichClick].prevX, chAll[whichClick].prevY, chAll[whichClick].prevW, chAll[whichClick].prevH,
                                chAll[whichClick].liveX, chAll[whichClick].liveY, chAll[whichClick].liveW, chAll[whichClick].liveH,
                                chAll[whichClick].audio, chAll[whichClick].volume);
                        chAll[whichClick].cameraIndex = cameraIndex;
                        openCamera(whichClick, cameraIndex);
                        initCamera(whichClick);
                    }
                    else {
                        Toast.makeText(ControlActivity.this,"无法打开摄像头！",Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CHOOSE_PHOTO) {
            Log.d("corelib", ">>>> choose photo.");
//            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//            startActivityForResult(intent, requestCode);
        } else if (requestCode == CHOOSE_CAMERA) {
            if (whichClick >= 0) {
                int cameraIndex = findCameraIndex();
//                    Log.d("corelib", ">>>> cameraIndex=" + cameraIndex);
                if (cameraIndex >= 0) {
                    chAll[whichClick].ch = mMixer.newCameraCh("camera", chAll[whichClick].loop, chAll[whichClick].surface,
                            chAll[whichClick].video, mPreviewWidth, mPreviewHeight, chAll[whichClick].prevX, chAll[whichClick].prevY, chAll[whichClick].prevW, chAll[whichClick].prevH,
                            chAll[whichClick].liveX, chAll[whichClick].liveY, chAll[whichClick].liveW, chAll[whichClick].liveH,
                            chAll[whichClick].audio, chAll[whichClick].volume);
                    chAll[whichClick].cameraIndex = cameraIndex;
                    openCamera(whichClick, cameraIndex);
                    initCamera(whichClick);
                }
                else {
                    Toast.makeText(ControlActivity.this,"无法打开摄像头！",Toast.LENGTH_LONG).show();
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 根据uri获取当前路径
     */
    public String getDataColumn(Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";//路径保存在downloads表中的_data字段
        final String[] projection = {column};
        try {
            cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case CHOOSE_PHOTO:
                if (resultCode==RESULT_OK) {
                    Uri originalUri = data.getData();
//                    surfaceHolderHandle(CHOOSE_PHOTO,originalUri);
                }
                break;
            case REQUEST_CODE:
                if (resultCode==RESULT_OK) {
                    Uri originalUri = data.getData();
                    String strPath = getDataColumn(originalUri, null, null);
//                    Log.d("corelib", "uri=" + originalUri);
//                    Log.d("corelib", "path=" + strPath);
//                    Log.d("corelib", ">>>> whichClicked=" +whichClicked);
                    if (whichClick >= 0)
                    {
                        chAll[whichClick].ch = mMixer.newCh(strPath, chAll[whichClick].loop, chAll[whichClick].surface,
                                chAll[whichClick].video, chAll[whichClick].prevX, chAll[whichClick].prevY, chAll[whichClick].prevW, chAll[whichClick].prevH,
                                chAll[whichClick].liveX, chAll[whichClick].liveY, chAll[whichClick].liveW, chAll[whichClick].liveH,
                                chAll[whichClick].audio, chAll[whichClick].volume);
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String getCPURateDesc111(){
        String path = "/proc/stat";// 系统CPU信息文件
        long totalJiffies[]=new long[2];
        long totalIdle[]=new long[2];
        int firstCPUNum=0;//设置这个参数，这要是防止两次读取文件获知的CPU数量不同，导致不能计算。这里统一以第一次的CPU数量为基准
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        Pattern pattern=Pattern.compile(" [0-9]+");
        for(int i=0;i<2;i++) {
            totalJiffies[i]=0;
            totalIdle[i]=0;
            try {
                fileReader = new FileReader(path);
                bufferedReader = new BufferedReader(fileReader, 8192);
                int currentCPUNum=0;
                String str;
                while ((str = bufferedReader.readLine()) != null&&(i==0||currentCPUNum<firstCPUNum)) {
                    if (str.toLowerCase().startsWith("cpu")) {
                        currentCPUNum++;
                        int index = 0;
                        Matcher matcher = pattern.matcher(str);
                        while (matcher.find()) {
                            try {
                                long tempJiffies = Long.parseLong(matcher.group(0).trim());
                                totalJiffies[i] += tempJiffies;
                                if (index == 3) {//空闲时间为该行第4条栏目
                                    totalIdle[i] += tempJiffies;
                                }
                                index++;
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if(i==0){
                        firstCPUNum=currentCPUNum;
                        try {//暂停50毫秒，等待系统更新信息。
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        double rate=-1;
        if (totalJiffies[0]>0&&totalJiffies[1]>0&&totalJiffies[0]!=totalJiffies[1]){
            rate=1.0*((totalJiffies[1]-totalIdle[1])-(totalJiffies[0]-totalIdle[0]))/(totalJiffies[1]-totalJiffies[0]);
        }
        DecimalFormat decimalFormat=new DecimalFormat(".00");
        String cpuUsed = decimalFormat.format(rate*100);
        return cpuUsed;
    }

    public  String getCPURateDesc(){
        String path = "/proc/stat";// 系统CPU信息文件
        long totalJiffies[]=new long[2];
        long totalIdle[]=new long[2];
        int firstCPUNum=0;//设置这个参数，这要是防止两次读取文件获知的CPU数量不同，导致不能计算。这里统一以第一次的CPU数量为基准
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        Pattern pattern=Pattern.compile(" [0-9]+");
        for(int i=0;i<2;i++) {
            totalJiffies[i]=0;
            totalIdle[i]=0;
            try {
                fileReader = new FileReader(path);
                bufferedReader = new BufferedReader(fileReader, 8192);
                int currentCPUNum=0;
                String str;
                while ((str = bufferedReader.readLine()) != null&&(i==0||currentCPUNum<firstCPUNum)) {
                    if (str.toLowerCase().startsWith("cpu")) {
                        currentCPUNum++;
                        int index = 0;
                        Matcher matcher = pattern.matcher(str);
                        while (matcher.find()) {
                            try {
                                long tempJiffies = Long.parseLong(matcher.group(0).trim());
                                totalJiffies[i] += tempJiffies;
                                if (index == 3) {//空闲时间为该行第4条栏目
                                    totalIdle[i] += tempJiffies;
                                }
                                index++;
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if(i==0){
                        firstCPUNum=currentCPUNum;
                        try {//暂停50毫秒，等待系统更新信息。
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        double rate=-1;
        if (totalJiffies[0]>0&&totalJiffies[1]>0&&totalJiffies[0]!=totalJiffies[1]){
            rate=1.0*((totalJiffies[1]-totalIdle[1])-(totalJiffies[0]-totalIdle[0]))/(totalJiffies[1]-totalJiffies[0]);
        }

        return String.format("cpu:%.2f",rate);
    }

    private long getAvailMemory() {// 获取android当前可用内存大小

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        //mi.availMem; 当前系统的可用内存
        return mi.availMem/1024;// 将获取的内存大小规格化
    }
    /**
     * 获取可用内存
     * @param
     * @return
     */
    private long getOwnMemFree(){
        long men=0;
        String line;
        String content = null;
        BufferedReader br = null;
        try {
            br=new BufferedReader(new FileReader("/proc/meminfo"));
            while((line=br.readLine())!=null){
                if (line.contains("MemFree")) {
                    content=line;
                    System.out.println(content);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (br!=null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        int trimTotal = getNumber(content);
//        int mBTotal=trimTotal/1024;
        men= trimTotal;
//        System.out.println(men);
        return men;
    }
    /**
     * 从字符串中获取数据
     */
    private int getNumber(String proc){
        String str = proc.trim();
        String str2="";
        if(str != null && !"".equals(str)){
            for(int i=0;i<str.length();i++){
                if(str.charAt(i)>=48 && str.charAt(i)<=57){
                    str2+=str.charAt(i);
                }
            }
        }
        return Integer.valueOf(str2);
    }
    /**
     * 获取系统总内存,返回字节单位为KB
     * @return 系统总内存
     */
    public static long getTotalMemory() {
        long totalMemorySize = 0;
        String dir = "/proc/meminfo";
        try {
            FileReader fr = new FileReader(dir);
            BufferedReader br = new BufferedReader(fr, 2048);
            String memoryLine = br.readLine();
            String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
            br.close();
            //将非数字的字符替换为空
            totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return totalMemorySize;
    }
}
